package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;

import com.bt.lms.ui.page.stu.PageEditApplyStuInfo;
import com.bt.lms.ui.page.common.action.pageenp.ApplyStuLabAction;
import com.bt.lms.ui.page.stu.PageMainStudentList;
import com.bt.lms.ui.page.stu.vo.EditRegStuInfoVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;

/**
 * 编辑报名学员信息保存按钮事件
 */
public class PageEditApplyStuInfoSaveBtnAction implements EventHandler {

    /**
     * 编辑报名学员信息界面
     */
    private PageEditApplyStuInfo pageEditApplyStuInfo;

    @Override
    public void handle(Event event) {

        //1.获取用户输入
        EditRegStuInfoVo editRegStuInfoVo = getInPrams();
        //2.验证用户输入
        String validDateMes = validateInParams(editRegStuInfoVo);
        //3.组包
        byte[] bytes = null;
        if (null == validDateMes) {
            //验证通过组包

            bytes = handleReqMes(editRegStuInfoVo);
        } else {


            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(validDateMes);
            alert.showAndWait();

            //提示程序终止
            return;
        }


        //4.组网
        Socket socket = getNet();

        //5.发送消息，发送的是消息包
        boolean flag = sendReqMes(socket, bytes);


        PageMainStudentList pageMainStudentList = new PageMainStudentList();
        Pane pane = ApplyStuLabAction.pageSkipInfo.getPane();
        Integer index = ApplyStuLabAction.pageSkipInfo.getIndex();
        pane.getChildren().set(index, pageMainStudentList);


    }


    /**
     * 发送消息
     *
     * @param socket 网
     * @param bytes  消息包
     * @return 是否成功
     */
    private boolean sendReqMes(Socket socket, byte[] bytes) {


        //发送

        try {
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();


            //6.接收服务端回应的消息
            RespMsg acceptRespMsg = acceptRespMsg(socket);

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }


        return true;
    }

    /**
     * 接收响应消息
     * @param socket 网络
     * @return 响应消息
     */
    private RespMsg acceptRespMsg(Socket socket) {

        byte[] buffer = new byte[1024];

        InputStream in = null;
        try {
            in = socket.getInputStream();
            in.read(buffer);



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        RespMsg respMsg = RespMsg.toRespMsg(buffer);
        String data = respMsg.getData();

        return respMsg ;
    }


    /**
     * 获取网络
     *
     * @return 网络
     */
    private Socket getNet() {

        String ip = "127.0.0.1";
        Integer serverPort = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, serverPort);
        } catch (Exception e) {
            return null;
        }


        return socket;
    }

    /**
     * 组包
     *
     * @param editRegStuInfoVo 用户输入
     * @return 消息
     */
    private byte[] handleReqMes(EditRegStuInfoVo editRegStuInfoVo) {


        //报名学员信息
        RegStuInfo regStuInfo = new RegStuInfo();


        //请求消息
        ReqMsg reqMsg = new ReqMsg();


        try {

            //业务类型
            reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_EDIT);
            //请求id时间戳
            long l = System.currentTimeMillis();
            reqMsg.setReqId(l);


            //vo转entity
            BeanUtils.copyProperties(regStuInfo, editRegStuInfoVo);

            String editRegStuStr = JSON.toJSONString(regStuInfo);

            reqMsg.setData(editRegStuStr);


        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        //掉方法
        byte[] bytes = reqMsg.toBytes();


        return bytes;
    }

    /**
     * 验证用户输入
     *
     * @param editRegStuInfoVo 用户输入的内容
     * @return 验证消息结果
     */
    private String validateInParams(EditRegStuInfoVo editRegStuInfoVo) {

        String mes = "";

        //帐号(电子邮箱)部分
        String account = editRegStuInfoVo.getAccount();

        String accountNull = "帐号（电子邮箱）不能为空\r\n";

        String accountLen = "帐号（电子邮箱）超过32为\r\n";


        if (account.equals("")) {//为空
            mes += accountNull;
        }
        if (account.length() > 32) {//长度超过32
            mes += accountLen;
        }


        //报名编号部分
        String registrationNo = editRegStuInfoVo.getRegistrationNo();
        String registrationNoLen = "报名编号不能超过32位\r\n";

        if (registrationNo.length() > 32) {//大于32位
            mes += registrationNoLen;
        }

        //姓名部分
        String name = editRegStuInfoVo.getName();
        String nameNull = "姓名必填\r\n";
        String nameLen = "姓名超过32位\r\n";

        if (name.equals("")) {
            mes += nameNull;
        }
        if (name.length() > 32) {
            mes += nameLen;
        }

        //出生日期部分
        LocalDate birthday = editRegStuInfoVo.getBirthday();
        String birthdayNull = "出生日期必填\r\n";
        String birthdayRange = "出生日期必须在当前日期150年之内\r\n";
        if (birthday == null) {//出生日期为空
            mes += birthdayNull;
        } else {
            LocalDate now = LocalDate.now();//当前日期
            int nowYear = now.getYear();//当前年
            int birthdayYear = birthday.getYear();//出生年
            if (birthdayYear > nowYear || nowYear - birthdayYear > 150) {
                mes += birthdayRange;

            }
        }

        //证件号码部分
        String idNo = editRegStuInfoVo.getIDNo();
        String idNoNull = "证件号码必填\r\n";
        String idNoLen = "证件号码需18位\r\n";
//        String idNoRange = "证件号码必须数字\r\n";
        if (idNo.equals("")) {//证件号码为空
            mes += idNoNull;
        }
        if (!(idNo.length() == 18)) {//证件号码不是18位
            mes += idNoLen;
        }


        //所属招生计划部分
        String enpPlan = editRegStuInfoVo.getEnpPlan();
        String enpPlanNull = "所属招生计划必填\r\n";
        if (enpPlan.equals("")) {//所属招生计划为空
            mes += enpPlanNull;
        }

        //电子邮箱部分
        String email = editRegStuInfoVo.getEmail();
        String emailNull = "电子邮箱必填\r\n";
//        String emailFormat = "电子邮箱输入的内容格式不正确\r\n";
        String emailLen = "电子邮箱长度在1-32之间\r\n";

//        Pattern emailCompile = Pattern.compile("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$");
//        Matcher emailMatcher = emailCompile.matcher(email);
//        boolean emailMatches = emailMatcher.matches();
        if (email.equals("")) {//电子邮箱为空
            mes += emailNull;
        }
//        if (emailMatches) {//电子邮箱格式不正确
//            mes += emailFormat;
//
//        }
        if (email.length() > 32) {
            mes += emailLen;
        }

        //移动电话部分
        String mobilePhone = editRegStuInfoVo.getMobilePhone();
        String mobilePhoneNull = "移动电话必填\r\n";
        String mobilePhoneRange = "移动电话11位\r\n";
        String mobilePhoneFormat = "移动电话必须是数字\r\n";

        if (mobilePhone.equals("")) {//移动电话为空
            mes += mobilePhoneNull;
        }
        if (!(mobilePhone.length() == 11)) {//移动电话不是11位
            mes += mobilePhoneRange;
        }
        try {
            //移动电话是数字
            long l = Long.parseLong(mobilePhone);
        } catch (NumberFormatException e) {
            mes += mobilePhoneFormat;
        }


        //qq部分
        String qq = editRegStuInfoVo.getQq();
        String qqNull = "qq必填\r\n";
        String qqNo = "qq必须是数字\r\n";
        String qqLen = "qq长度超过10位";

        if (qq.equals("")) { //qq为空
            mes += qqNull;
        }
        try {
            long l = Long.parseLong(qq);//必须是数字
        } catch (NumberFormatException e) {
            mes += qqNo;

        }
        if (qq.length() > 10) {
            mes += qqLen;
        }

        //微信部分
        String weChat = editRegStuInfoVo.getWeChat();
        String weChatNull = "微信必填";
        if (weChat.equals("")) {
            mes += weChatNull;

        }


        //返回结果集
        if ("".equals(mes)) {
            return null;

        } else {
            return mes;

        }


    }


    /**
     * 获取用户输入的内容
     *
     * @return
     */
    private EditRegStuInfoVo getInPrams() {

        //封装成VO对象
        EditRegStuInfoVo editRegStuInfoVo = new EditRegStuInfoVo();

        //帐号（电子邮箱）部分
        TextField accountTF = (TextField) pageEditApplyStuInfo.lookup("#accountTF");
        String accountStr = accountTF.getText().trim();//获取到内容 并去掉无效空格
        editRegStuInfoVo.setAccount(accountStr);

        //报名编号部分
        TextField applyNumTF = (TextField) pageEditApplyStuInfo.lookup("#applyNumTF");
        String applyNumStr = applyNumTF.getText().trim();
        editRegStuInfoVo.setRegistrationNo(applyNumStr);

        //姓名部分
        TextField nameTF = (TextField) pageEditApplyStuInfo.lookup("#nameTF");
        String nameStr = nameTF.getText().trim();
        editRegStuInfoVo.setName(nameStr);

        //性别部分
        ComboBox genderCB = (ComboBox) pageEditApplyStuInfo.lookup("#genderCB");
        String genderCBValue = (String) genderCB.getValue();
        Integer genderType = -1;
        switch (genderCBValue) {
            case "男":
                genderType = 1;
                break;

            case "女":
                genderType = 2;
                break;

        }
        editRegStuInfoVo.setGender(genderType);

        //出生日期部分
        DatePicker birthdayDP = (DatePicker) pageEditApplyStuInfo.lookup("#birthdayDP");
        LocalDate birthdayDPValue = birthdayDP.getValue();
        editRegStuInfoVo.setBirthday(birthdayDPValue);

        //证件类型部分
        ComboBox IDTypeCB = (ComboBox) pageEditApplyStuInfo.lookup("#IDTpeCB");
        String IDTypeValue = (String) IDTypeCB.getValue();
        Integer IDType = -1;
        switch (IDTypeValue) {
            case "身份证":
                IDType = 1;
                break;

            case "军官证":
                IDType = 2;
                break;
        }
        editRegStuInfoVo.setCertType(IDType);

        //证件号码部分
        TextField IDNumTF = (TextField) pageEditApplyStuInfo.lookup("#IDNumTF");
        String IDNumStr = IDNumTF.getText().trim();
        editRegStuInfoVo.setIDNo(IDNumStr);


        //所属招生计划部分
        TextField ofEnPTF = (TextField) pageEditApplyStuInfo.lookup("#ofEnPTF");
        String ofEnPTStr = ofEnPTF.getText().trim();
        editRegStuInfoVo.setEnpPlan(ofEnPTStr);

        //电子邮箱部分
        TextField emailTF = (TextField) pageEditApplyStuInfo.lookup("#emailTF");
        String emailStr = emailTF.getText().trim();
        editRegStuInfoVo.setEmail(emailStr);

        //移动电话部分
        TextField movePhoneTF = (TextField) pageEditApplyStuInfo.lookup("#movePhoneTF");
        String movePhoneStr = movePhoneTF.getText().trim();
        editRegStuInfoVo.setMobilePhone(movePhoneStr);

        //qq部分
        TextField qqTF = (TextField) pageEditApplyStuInfo.lookup("#qqTF");
        String qqStr = qqTF.getText().trim();
        editRegStuInfoVo.setQq(qqStr);


        //微信部分
        TextField weChatTF = (TextField) pageEditApplyStuInfo.lookup("#weChatTF");
        String weCharStr = weChatTF.getText().trim();
        editRegStuInfoVo.setWeChat(weCharStr);


        return editRegStuInfoVo;

    }

    /**
     * 将int转成byte数组
     *
     * @param value
     * @return
     */
    public static byte[] intoBytes(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value >> 24) & 0xFF);
        src[1] = (byte) ((value >> 16) & 0xFF);
        src[2] = (byte) ((value >> 8) & 0xFF);
        src[3] = (byte) (value & 0xFF);

        return src;
    }


    public PageEditApplyStuInfo getPageEditApplyStuInfo() {
        return pageEditApplyStuInfo;
    }

    public void setPageEditApplyStuInfo(PageEditApplyStuInfo pageEditApplyStuInfo) {
        this.pageEditApplyStuInfo = pageEditApplyStuInfo;
    }
}
